<?php
/**
 * 小程序api
 * Created by Forever.
 * User: Forever
 * Date: 2018/8/27 0027
 * Time: 上午 9:39
 */
namespace app\api\model;
use think\Cache;
use \think\Model;
use \think\Db;
use EasyWeChat\Foundation\Application;
class Mini extends Model{

    protected static $tb = [
        'shop'    => 'shop',
        'member'  => 'member',
        'role'  => 'role', 
        'message'=>'message',
        'order' =>'order', 
        'user' =>'user', 
        'product' =>'product',
        'follow_shop'=>'follow_shop',
        'follow_product'=>'follow_product'
    ]; 

    protected $easywechat;
    protected $options;
    protected $miniProgram;
    protected $projecturl;
    public function initialize()
    {
        $this->options = config('wechat.options');
        $this->projecturl = config('wechat.projecturl');
        $this->easywechat = new Application($this->options);
        $this->miniProgram = $this->easywechat->mini_program;
        $this->accessToken = $this->easywechat->access_token; 

    }


    /*
    *获取小程序token
     */
    public function getMiniToken()
    {
         $res = cache('mini_access_token'); 
         if (empty($res) || $res['last_time'] < time()) {
            $accessToken = $this->miniProgram->access_token; // EasyWeChat\Core\AccessToken 实例
            $token = $accessToken->getToken(); // token 字符串
            if ($token) {
                $result['access_token'] = $token;
                $result['expires_in'] = 7200;
                $result['last_time'] = time() + $result['expires_in'];
                cache('mini_access_token', $result);
                $res = cache('mini_access_token');
                return $res['access_token'];
            } else {
                return false;
            }
         } else {
             return $res['access_token'];
         }
    }

     /*
      * 获取SessionKey
      *
      *  */
    public function getSessionKey($data=[]){
        $code = $data['code'];
        $info = $this->miniProgram->sns->getSessionKey($code); 
        if(!empty($info['errcode'])){
            return  $info['errcode'];
        }
        $openId = $info['openid'];
        $field = "id,name,nickname,mobile,is_user,user_id,headimg,miniopenid as openid";
        $member = Db::name(self::$tb['member'])->where('miniopenid',$openId)->field($field)->find();
        if(!$member){
            return false;
        }
        if($member['is_user'] == 1){
            $field= "u.id,u.phone,u.name,u.flow_money,u.sale_total,u.role_id,u.flow_money,u.shop_id,r.name as role_name";
            $users = Db::name(self::$tb['user'])->alias("u")->join("jun_role r","r.id=u.role_id","left")
            ->where("u.id",$member['user_id'])->field($field)->find();
            $member['phone'] = $users['phone'];
            $member['flow_money'] = $users['flow_money'];
            $member['sale_total'] = $users['sale_total'];
            $member['role_name'] = $users['role_name'];
            $member['shop_id'] = $users['shop_id'];
            //$member['order_num'] =Db::name(self::$tb['order'])->where(['uid'=>$member['id'],'status'=>["in","1,2"]])->count();
        } else{
            $member['flow_car'] = Db::name(self::$tb['follow_product'])->where("member_id",$member['id'])->count();
            $member['flow_shop'] = Db::name(self::$tb['follow_shop'])->where("member_id",$member['id'])->count();
        } 
        $member['order_num'] =Db::name(self::$tb['order'])->where(['uid'=>$member['id'],'status'=>["in","1,2"]])->count();
        return $member;
    }

    /*
     * 获取用户信息
     *
     */
    public function getUserInfo($data=[]){
        if(isset($data['code'])  && !empty($data['code'])){
            $code = $data['code']; 
            $info = $this->miniProgram->sns->getSessionKey($code);  
            if(!empty($info['errcode'])){
              return $info; 
            }
        }
        $sessionKey = $info['session_key'];
        $iv = $data['iv'];
        $encryptData = $data['encryptData'];
        $userinfo = $this->miniProgram->encryptor->decryptData($sessionKey, $iv, $encryptData);  
        if(!empty($userinfo['errcode'])){
           return $userinfo; 
        }else{
            $openid = $userinfo['openId']; 
            $user = Db::name("member")->where('miniopenid',$openid)->find();
            if($user){  
              return $user;
            }else{
              //新增
              $new = [
                'miniopenid'=>$openid,
                'nickname'=>$userinfo['nickName'],
                'headimg'=>$userinfo['avatarUrl'],
                'sex'=>$userinfo['gender'], 
                "cs_id"=>isset($data['cs_id'])?$data['cs_id']:0,
                'province'=>$userinfo['province'],
                'city'=>$userinfo['city'],
                'addtime'=>time()
              ];
              $new_id = Db::name('member')->insertGetId($new);
              $new['id'] = $new_id;
              $new['flow_car'] = 0;
              $new['flow_shop'] = 0; 
              $new['order_num'] = 0;
              return $new;
            }  
        }
    }

    /***
    * 获取小程序的二维码
    * @param string $spath //二维码路径
    * @param int $web_id   //web_id
    * @return bool
    */
    public function getQrCode($path){     
       $code = $this->easywechat->app_code->getQrCode($path,300); 
       return $code;
    }

    /***
    * 生成进入微信小程序二维码
    * @param string $spath //二维码路径
    * @param int $web_id   //web_id
    * @return bool
    */
    public function getwxcardqrcode($qr_url,$module='wechat')
    {
        $access_token = $this->getToken();
        if(!$access_token) { return false; } 
        $spath="/src/pages/home/home";
        $spath .= '?redirect_url='.urlencode($qr_url);
        $url = $this->projecturl['getwxacode'].$access_token;
        $width = 430;
        $data='{"path":"'.$spath.'","width":'.$width.'}';
        $result = model('member/MemberCard')->request_post($url,$data); 
        //将生成的小程序码存入相应文件夹下
        $path = ROOT_PATH.'public'.DS.'uploadfile'.DS.config('web_id').DS.$module;
        if(!file_exists($path))  mkdir($path, 0755, true);
        $filename = time().".png";
        file_put_contents($path.DS.$filename,$result);
        //上传七牛上的图片，因为返回的图片路径好慢暂时不用
        $result = \think\Loader::controller('wechat/Base','controller')->save_img_action($path.DS.$filename,'yaliapi'.'/'.config('web_id').'/'.$module);

        return $result['data'];
    }
}